import { asyncRoutes, constantRoutes } from '@/router'
import { Message } from 'element-ui'
/**
 * Use meta.role to determine if the current user has permission
 * @param menu
 * @param route
 */
function hasPermission(menu, route) {
  let result = false
  // * 404
  if (route.path === '*') {
    return true
  }
  // 详情页等
  if (route.meta && route.meta.subRoute === true) {
    return hasPermission(menu, { path: route.meta.parentPath })
  }
  menu.forEach((menuItem) => {
    if (menuItem.level === 2 && menuItem.path === route.path) {
      result = true
    }
    if (!result && menuItem.children) {
      if (hasPermission(menuItem.children, route)) {
        result = true
      }
    }
  })
  return result
}

function authorization(routes, name) {
  let result = false
  routes.forEach((routeItem) => {
    if (routeItem.name && routeItem.name === name) {
      result = true
    }
    if (!result && routeItem.children) {
      if (authorization(routeItem.children, name)) {
        result = true
      }
    }
  })
  return result
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, menu) {
  const res = []
  routes.forEach((routeItem) => {
    const temp = { ...routeItem }
    if (hasPermission(menu, temp)) {
      if (temp.children) {
        temp.children = filterAsyncRoutes(temp.children, menu)
      }
      res.push(temp)
    }
  })
  return res
}

const state = {
  hasAsyncRoutes: false,
  routes: [],
  addRoutes: [],
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = [...constantRoutes, ...routes]
  },
  RESET_ROUTES: (state) => {
    state.addRoutes = []
    state.routes = []
    state.hasAsyncRoutes = false
  },
  SET_ASYNC_ROUTES: (state) => {
    state.hasAsyncRoutes = !state.hasAsyncRoutes
  },
}

const actions = {
  setAsyncRoutes({ commit }) {
    commit('SET_ASYNC_ROUTES')
  },
  generateRoutes({ commit }, menu) {
    return new Promise((resolve) => {
      // try {
      //   let objList = {} // 缓存button
      //   menu.forEach((item, index) => {
      //     objList[item.path] = item.buttons
      //     item.children.forEach((item1, index1) => {
      //       objList[item.path + '/' + item1.path] = item1.buttons
      //     })
      //   })
      //   localStorage.setItem('jurisdiction', JSON.stringify(objList))
      // } catch {}

      commit('RESET_ROUTES')
      let accessedRoutes = filterAsyncRoutes(asyncRoutes, menu)
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_ASYNC_ROUTES')
      resolve(accessedRoutes)
    })
  },
  // 跳转路由权限验证
  routeAuthorization({ state }, name) {
    return new Promise((resolve, reject) => {
      if (authorization(state.routes, name)) {
        resolve()
      } else {
        Message.error('暂无权限')
        reject()
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
